<template>
  <div class="login-modal">
    <n-modal show :close-on-esc="false" :mask-closable="false">
      <n-card style="width: 400px" :bordered="false" size="huge">
        <n-space vertical size="large">
          <n-space size="large" justify="center">
            <n-avatar round size="large" :color="themeVars.primaryColor">
              <n-icon :component="PlanetOutline"></n-icon>
            </n-avatar>
          </n-space>
          <n-form
              ref="formInstRef"
              :model="userLoginParam"
              :rules="rules"
              label-placement="left"
          >
            <n-form-item path="username">
              <n-input
                  v-model:value="userLoginParam.username"
                  size="large"
                  placeholder="请输入用户名"
                  clearable>
                <template #prefix>
                  <n-icon :component="Person"/>
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="pwd">
              <n-input
                  v-model:value="userLoginParam.pwd"
                  size="large"
                  type="password"
                  placeholder="请输入密码"
                  show-password-on="mousedown"
                  clearable>
                <template #prefix>
                  <n-icon :component="Key"/>
                </template>
              </n-input>
            </n-form-item>
            <n-form-item path="captcha" v-if="showCaptcha">
              <n-input-group>
                <n-input
                    :style="{width: '50%'}"
                    size="large"
                    v-model:value="userLoginParam.captcha"
                    placeholder="请输入验证码"
                    clearable/>
                <n-image
                    width="160"
                    height="40"
                    :style="{cursor: 'pointer'}"
                    preview-disabled
                    :src="`data:image/png;base64,` + userLoginVO.captchaImage"
                    @click="getCaptcha"/>
              </n-input-group>
            </n-form-item>
            <n-button type="primary" round size="large" block @click="login">
              <template #icon>
                <n-icon :component="LoginOutlined"/>
              </template>
              登录
            </n-button>
          </n-form>
        </n-space>
      </n-card>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import {reactive, toRefs, ref} from "vue";
import {FormInst, useThemeVars} from "naive-ui";
import {Person, Key, PlanetOutline} from "@vicons/ionicons5";
import {LoginOutlined} from "@vicons/antd";
import UserApi from "../../api/UserApi";
import {UserLoginParam, UserLoginVO} from "../../model/User";
import Rsa from "../../util/rsa";
import store from "../../store";
import {useRouter} from "vue-router";
import {storeToRefs} from "pinia";

const router = useRouter();
const appStore = store();
const {activeTab} = storeToRefs(appStore);
const formInstRef = ref<FormInst | null>(null);
const themeVars = useThemeVars();
const data = reactive({
  userLoginVO: new UserLoginVO(),
  showCaptcha: false,
  userLoginParam: new UserLoginParam()
});

const {userLoginVO, showCaptcha, userLoginParam} = toRefs(data);

const getCaptcha = (): void => {
  UserApi.getCaptcha()
      .then(response => {
        data.userLoginVO = response;
        data.userLoginParam.captchaToken = data.userLoginVO.captchaToken;
      });
}

const login = (): void => {
  formInstRef.value?.validate((errors) => {
        if (!errors) {
          UserApi.login(Rsa(JSON.stringify(data.userLoginParam)))
              .then(response => {
                data.userLoginVO = response;
                data.showCaptcha = data.userLoginVO.captchaToken != null;
                data.userLoginParam.captchaToken = data.userLoginVO.captchaToken;
                if (response.token) {
                  appStore.setToken(response.token);
                  appStore.setUsername(data.userLoginParam.username as string);
                  router.push(activeTab.value.length > 0 ? activeTab.value : "/");
                }
              });
        }
      },
      (rule) => {
        if (data.showCaptcha) {
          return true;
        }
        return rule?.key != "captcha";
      }
  )
}

const rules = {
  username: {
    required: true,
    message: "请输入用户名",
    trigger: ["blur"]
  },
  pwd: {
    required: true,
    message: "请输入密码",
    trigger: ["blur"]
  },
  captcha: {
    key: "captcha",
    required: true,
    message: "请输入验证码",
    trigger: ["blur"]
  },
};
</script>
<style lang="scss" scoped>
.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  background: radial-gradient(#63e2b7, black);
}
</style>